package two.chapter_1.c1_3;

import java.util.Iterator;

/**
 * 文本编辑器缓冲区
 */
public class Buffer implements Iterable<Character>{
    private Stack<Character> stack;
    private Stack<Character> temp;
    private int cursor;
    private int size;
    public Buffer(){
        stack=new LinkStack<>();
        temp=new LinkStack<>();
    }

    /**
     * 在光标位置插入字符c
     * @param c
     */
    public void insert(char c){
        int pop=size-cursor;
        for (int i=0;i<pop;i++) {
            temp.push(stack.pop());
        }
        stack.push(c);
        size++;
        cursor++;
        for (int i=0;i<pop;i++){
            stack.push(temp.pop());
        }
    }

    /**
     * 删除并返回光标位置的字符
     * @return
     */
    public char delete(){
        int pop=size-cursor;
        for (int i=0;i<pop;i++) {
            temp.push(stack.pop());
        }

        char c=stack.pop();
        size--;
        for (int i=0;i<pop;i++) {
            stack.push(temp.pop());
        }

        return c;
    }

    /**
     * 将光标向左移动k个位置
     * @param k
     */
    public void left(int k){
        if (cursor>k){
            cursor=cursor-k;
        }
    }
    public void right(int k){
        if (k+cursor<=size){
            cursor=cursor+k;
        }
    }

    public int size(){
        return size;
    }


    @Override
    public Iterator<Character> iterator() {
        return stack.iterator();
    }

}
